package com.lvyq.myplayer.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.current.CurrentPlayLstAdapter
import com.lvyq.myplayer.base.BaseActivity
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.common.util.ImgAnimatorUtils
import com.lvyq.myplayer.common.util.ManifestUtils
import com.lvyq.myplayer.common.util.UpVersion
import com.lvyq.myplayer.service.AudioService
import com.lvyq.myplayer.util.FragmentUtil
import com.roughike.bottombar.BottomBar
import com.squareup.picasso.Picasso
import org.jetbrains.anko.find

class MainActivity : BaseActivity(),UpVersion {

    override var currentPlayAdapter: CurrentPlayLstAdapter? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    @RequiresApi(Build.VERSION_CODES.R)
    override fun initData() {

        initPlayBoxService()

        //检测新版本
        checkVersion(getAppVersionCode(this),this,false)

    }

    /**
     * 播放栏服务初始化
     */
    private fun initPlayBoxService() {
        initMainPlayBoxListener()
        currentPlayAdapter=getAdapter()
        initAudioPlayLst(this)
        //设置viewpage2 适配器
        recreateViewPagerAdapter()
        initMainPlayStateChangeUI()
        //updateMainPlayStateBtn(false)
        var songInfo = MainAudioSharedPrefsManager.getSongInfo(this)
        var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this)
        //通过audioservice 播放,混合启动，保证退出当前页仍然播放
        val audioIntent = Intent(this, AudioService::class.java)
        //传递值到AudioService中
        audioIntent.putExtra("data",songInfo)
        audioIntent.putExtra("from",-1)
        audioIntent.putExtra("position",currentAudioPosition?.toInt())
        //绑定 BIND_AUTO_CREATE 服务未创建时创建并绑定
        bindService(audioIntent,connection, BIND_AUTO_CREATE)
        //启动
        startService(audioIntent)
    }


    /**
     * 更新安装-完整应用包
     */
    override fun apkDownAndInstall(patchUrl: String, context: Context) {
        //读写权限
        if (!ManifestUtils.checkStoragePermission(this))  return
        //应用内安装程序权限
        if (!ManifestUtils.checkInstallAPPPermission(this))  return
        super.apkDownAndInstall(patchUrl, context)
    }

    private fun getAdapter(): CurrentPlayLstAdapter {
        return CurrentPlayLstAdapter(this)
    }

    override fun initListener() {
        var bottomBar = find<BottomBar>(R.id.bottomBar)
        bottomBar.setOnTabSelectListener{
            var beginTransaction = supportFragmentManager.beginTransaction()
            FragmentUtil.fragmentUtil.getFragment(it)?.let { i ->
                beginTransaction.replace( R.id.container, i,it.toString())
                beginTransaction.commit()
            }
        }



    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection)
    }

}